﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
using PessModel;
using PessMvc.Helpers;
namespace PessMvc.Lib
{
    public class DisplayNameModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        //private static PESSEntities db;
        //public DisplayNameModelMetadataProvider():base()
        //{
        //    if(db==null)
        //    {
        //        db = new PESSEntities();
        //    }
        //    else
        //    {
        //        db.Ch
        //    }
        //}
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            ModelMetadata modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
            if (containerType!=null&&containerType.Equals(typeof(PessModel.Archive)) )//&& propertyName == "ProjectTitle")//attributes.OfType<DisplayNameAttribute>().Count()!=0)
            {
                if (HttpContext.Current.Session["ActivityID"] != null)
                {
                    int activityID = (int)HttpContext.Current.Session["ActivityID"];
                    using (PESSEntities db = new PESSEntities())
                    {
                        var displayname = db.ArchiveDisplayNames.Where(x => x.PropertyName.Trim().ToUpper() == propertyName.ToUpper() && x.ActivityID == activityID).FirstOrDefault();
                        if (displayname != null)
                        {
                            modelMetadata.DisplayName = displayname.DisplayName;
                            modelMetadata.ShowForDisplay = false;// Utility.IsVisible(displayname.Visibility);
                            modelMetadata.ShowForEdit = false;// Utility.IsVisible(displayname.Visibility);
                            //Func<int?,bool> checkVisibility=(int? visibility)=>{
                            //    if (visibility==null)
                            //    {
                            //        return true;
                            //    }
                            //    else if (visibility==1)
                            //    {
                            //        return true;
                            //    }
                            //    else
                            //    {
                            //        return false;
                            //    }
                            //};
                            //modelMetadata.HideSurroundingHtml = checkVisibility(displayname.Visibility);
                        }
                    }
                }
            }
            return modelMetadata;
        }
        //protected override void Dispose()
        //{
        //    db.Dispose();
        //}
    }
}